package api

import (
	"context"
	"github.com/gin-gonic/gin"
	"kuangstudy-mall/apis/order-web/microservices"
	context2 "kuangstudy-mall/apis/order-web/models/context"
	"kuangstudy-mall/apis/order-web/proto"
	"kuangstudy-mall/apis/order-web/validation"
	"strconv"
	"strings"
)

type ShopcartApi struct {
	BaseApi
}

/*
*
查询用户购物车信息
*/
func (api *ShopcartApi) FindCartListByUserId(ctx *gin.Context) {
	userId := ctx.GetUint64("userId")
	cartUserInfo := proto.CartUserInfo{
		UserId: userId,
	}
	goodListResponse, err := microservices.GetNacosOrderClient().FindCartListByUserId(context.Background(), &cartUserInfo)
	if err != nil {
		api.handlerGrpcError(err, ctx)
		return
	}
	api.OK(goodListResponse, ctx)
}

/*
*
查询用户购物车信息
*/
func (api *ShopcartApi) AddGoodsToShoppingCart(ctx *gin.Context) {
	saveShopcartContxt := context2.SaveShopcartContxt{}
	err := ctx.ShouldBindJSON(&saveShopcartContxt)
	if err != nil {
		api.FailCodeMsgAny(603, validation.GetErrors(err, saveShopcartContxt), ctx)
		return
	}
	userId := ctx.GetUint64("userId")
	cartItemRequest := proto.CartItemRequest{
		UserId:  userId,
		Nums:    saveShopcartContxt.Nums,
		GoodsId: saveShopcartContxt.GoodsId,
		Checked: saveShopcartContxt.Checked,
	}
	shopcartItemsResponse, err := microservices.GetNacosOrderClient().AddGoodsToShoppingCart(context.Background(), &cartItemRequest)
	if err != nil {
		api.handlerGrpcError(err, ctx)
		return
	}
	api.OK(shopcartItemsResponse, ctx)
}

/*
*
修改购物车状态比如：选中，数量
*/
func (api *ShopcartApi) UpdateShoppingCartStatus(ctx *gin.Context) {
	saveShopcartContxt := context2.SaveShopcartContxt{}
	err := ctx.ShouldBindJSON(&saveShopcartContxt)
	if err != nil {
		api.FailCodeMsgAny(603, validation.GetErrors(err, saveShopcartContxt), ctx)
		return
	}
	userId := ctx.GetUint64("userId")
	cartItemRequest := proto.CartItemRequest{
		UserId:  userId,
		GoodsId: saveShopcartContxt.GoodsId,
		Nums:    saveShopcartContxt.Nums,
		Checked: saveShopcartContxt.Checked,
	}
	shopcartItemsResponse, err := microservices.GetNacosOrderClient().UpdateShoppingCartStatus(context.Background(), &cartItemRequest)
	if err != nil {
		api.handlerGrpcError(err, ctx)
		return
	}
	api.OK(shopcartItemsResponse, ctx)
}

/*
*
删除购物车
*/
func (api *ShopcartApi) DeleteShoppingCartItems(ctx *gin.Context) {
	ids, _ := ctx.GetQuery("ids")
	splitIds := strings.Split(ids, ",")
	var shopcartIds []uint64
	for _, id := range splitIds {
		parseUint, _ := strconv.ParseUint(id, 10, 64)
		shopcartIds = append(shopcartIds, parseUint)
	}
	cartItemsRequest := proto.CartItemsRequest{
		Ids: shopcartIds,
	}
	shopcartItemsResponse, err := microservices.GetNacosOrderClient().DeleteShoppingCartItems(context.Background(), &cartItemsRequest)
	if err != nil {
		api.handlerGrpcError(err, ctx)
		return
	}
	api.OK(shopcartItemsResponse, ctx)
}
